package com.dolphin.aiagentplatform.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dolphin.aiagentplatform.ai.config.ChatStorageConfig;
import com.dolphin.aiagentplatform.ai.repository.ChatIdRepository;
import com.dolphin.aiagentplatform.mapper.ChatSessionMapper;
import com.dolphin.aiagentplatform.model.dto.ChatSessionInfoDTO;
import com.dolphin.aiagentplatform.model.entity.ChatMessage;
import com.dolphin.aiagentplatform.model.entity.ChatSession;
import com.dolphin.aiagentplatform.service.ChatMessageService;
import com.dolphin.aiagentplatform.service.ChatSessionService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 聊天会话服务实现类
 */
@Service
@Slf4j
public class ChatSessionServiceImpl extends ServiceImpl<ChatSessionMapper, ChatSession>
        implements ChatSessionService {

    @Resource
    private ChatIdRepository inMemoryChatIdRepository;

    @Resource
    @Lazy
    private ChatMessageService chatMessageService;

    @Override
    public void saveChatSession(String chatId, Long userId, String agentType) {
        // 检查聊天会话是否已存在
        ChatSession existingSession = lambdaQuery()
                .eq(ChatSession::getChatId, chatId)
                .eq(ChatSession::getIsDelete, 0)
                .one();

        if (existingSession != null) {
            // 已存在，更新最后消息时间
            ChatSession updateSession = new ChatSession();
            updateSession.setId(existingSession.getId());
            updateSession.setLastMessageTime(new Date());
            updateById(updateSession);
            log.debug("更新聊天会话, chatId: {}", chatId);
        } else {
            // 不存在，创建新会话
            ChatSession chatSession = new ChatSession();
            chatSession.setChatId(chatId);
            chatSession.setUserId(userId);
            chatSession.setAgentType(agentType);
            chatSession.setStatus(1); // 活跃状态
            chatSession.setLastMessageTime(new Date());
            save(chatSession);
            log.debug("创建新聊天会话, chatId: {}, userId: {}, agentType: {}", chatId, userId, agentType);
        }
    }

    @Override
    public List<String> getChatIdListByAgentType(String agentType) {
        List<ChatSession> chatSessions = lambdaQuery()
                .eq(ChatSession::getAgentType, agentType)
                .eq(ChatSession::getIsDelete, 0)
                .orderByDesc(ChatSession::getLastMessageTime)
                .list();

        return chatSessions.stream()
                .map(ChatSession::getChatId)
                .collect(Collectors.toList());
    }

    @Override
    public List<String> getChatIdListByUserId(Long userId, String agentType) {
        List<ChatSession> chatSessions = lambdaQuery()
                .eq(ChatSession::getUserId, userId)
                .eq(ChatSession::getAgentType, agentType)
                .eq(ChatSession::getIsDelete, 0)
                .orderByDesc(ChatSession::getLastMessageTime)
                .list();

        return chatSessions.stream()
                .map(ChatSession::getChatId)
                .collect(Collectors.toList());
    }

    @Override
    public String getLatestChatIdByUserId(Long userId, String agentType) {
        ChatSession latestSession = lambdaQuery()
                .eq(ChatSession::getUserId, userId)
                .eq(ChatSession::getAgentType, agentType)
                .eq(ChatSession::getStatus, 1) // 活跃状态
                .eq(ChatSession::getIsDelete, 0)
                .orderByDesc(ChatSession::getLastMessageTime)
                .last("LIMIT 1")
                .one();

        return latestSession != null ? latestSession.getChatId() : null;
    }

    @Override
    public boolean updateLastMessageTime(String chatId) {
        ChatSession chatSession = lambdaQuery()
                .eq(ChatSession::getChatId, chatId)
                .eq(ChatSession::getIsDelete, 0)
                .one();

        if (chatSession != null) {
            ChatSession updateSession = new ChatSession();
            updateSession.setId(chatSession.getId());
            updateSession.setLastMessageTime(new Date());
            return updateById(updateSession);
        }

        return false;
    }

    @Override
    public boolean archiveChat(String chatId) {
        ChatSession chatSession = lambdaQuery()
                .eq(ChatSession::getChatId, chatId)
                .eq(ChatSession::getIsDelete, 0)
                .one();

        if (chatSession != null) {
            ChatSession updateSession = new ChatSession();
            updateSession.setId(chatSession.getId());
            updateSession.setStatus(0); // 归档状态
            return updateById(updateSession);
        }

        return false;
    }

    @Override
    public ChatSessionInfoDTO getChatSessionInfo(String chatId) {
        ChatSession chatSession = lambdaQuery()
                .eq(ChatSession::getChatId, chatId)
                .eq(ChatSession::getIsDelete, 0)
                .one();

        if (chatSession == null) {
            return null;
        }

        // 获取该会话的完整对话数量（system+user+assistant为一组）
        int conversationCount = chatMessageService.getConversationCount(chatId);

        // 获取最后一条AI消息，获取其模型类型
        List<ChatMessage> lastMessages = chatMessageService.lambdaQuery()
                .eq(ChatMessage::getChatId, chatId)
                .eq(ChatMessage::getRole, "assistant")
                .eq(ChatMessage::getIsDelete, 0)
                .orderByDesc(ChatMessage::getCreateTime)
                .last("LIMIT 1")
                .list();

        String modelType = lastMessages.isEmpty() ? null : lastMessages.get(0).getModelType();

        // 构建返回对象
        return ChatSessionInfoDTO.builder()
                .chatId(chatSession.getChatId())
                .title(chatSession.getTitle())
                .createTime(chatSession.getCreateTime())
                .lastMessageTime(chatSession.getLastMessageTime())
                .messageCount(conversationCount)
                .modelType(modelType)
                .agentType(chatSession.getAgentType())
                .status(chatSession.getStatus())
                .build();
    }

    @Override
    public List<ChatSessionInfoDTO> getChatSessionInfoBatch(List<String> chatIds) {
        List<ChatSessionInfoDTO> result = new ArrayList<>();
        for (String chatId : chatIds) {
            ChatSessionInfoDTO info = getChatSessionInfo(chatId);
            if (info != null) {
                result.add(info);
            }
        }

        return result;
    }

    @Override
    public List<ChatSessionInfoDTO> getChatSessionInfoByUserId(Long userId, String agentType) {
        // 获取用户的所有聊天ID
        List<String> chatIds = getChatIdListByUserId(userId, agentType);
        return getChatSessionInfoBatch(chatIds);
    }

    @Override
    public boolean updateChatSessionTitle(String chatId, String title) {
        ChatSession chatSession = lambdaQuery()
                .eq(ChatSession::getChatId, chatId)
                .eq(ChatSession::getIsDelete, 0)
                .one();

        if (chatSession != null) {
            ChatSession updateSession = new ChatSession();
            updateSession.setId(chatSession.getId());
            updateSession.setTitle(title);
            return updateById(updateSession);
        }

        return false;
    }

    @Override
    public boolean deleteChatSession(String chatId, Long userId) {
        boolean updateResult = lambdaUpdate()
                .eq(ChatSession::getChatId, chatId)
                .eq(ChatSession::getUserId, userId)
                .set(ChatSession::getIsDelete, 1)
                .update();

        if (updateResult) {
            log.info("删除聊天会话: chatId: {}, userId: {}", chatId, userId);
        } else {
            log.warn("删除聊天会话失败：会话不存在或无权限. chatId: {}, userId: {}", chatId, userId);
        }

        return updateResult;
    }
}




